const yargs = require('yargs')
const fs = require('fs')
yargs.parse = () => { console.log('do do nothing') }
const http = require('http')
const terminalizer = require('terminalizer')
const render = require('./render.js')

const server = http.createServer((req, res) => {
    try {
        // 设置响应的状态码和头部信息
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        if (req.method === 'POST' && req.url === '/render') {
            let body = '';

            req.on('data', (chunk) => {
                body += chunk;
            });

            req.on('end', () => {
                let recordingFile = {
                    json: di.yaml.load(body),
                    raw: body
                }
                render.handler({
                    recordingFile: recordingFile,
                    step: 1,
                    res: res,
                    host: req.headers.host
                })
            }
            );
        }
        else if (req.method === 'GET' && req.url === '/index') {
            fs.readFile('index.html', 'utf8', (err, data) => {
                if (err) {
                    res.statusCode = 500;
                    res.end('Internal Server Error');
                } else {
                    res.statusCode = 200;
                    res.setHeader('Content-Type', 'text/html');
                    res.end(data);
                }
            });
        }
        else if (req.method === 'GET' && req.url.endsWith('.gif')) {
            const url = new URL(req.url, `http://${req.headers.host}`);
            const fileName = path.basename(url.pathname);

            if (fileName.endsWith('.gif')) {
                const filePath = path.join(__dirname, fileName);

                fs.access(filePath, fs.constants.F_OK, (err) => {
                    if (err) {
                        res.statusCode = 404;
                        res.end('File not found');
                    } else {
                        const fileStream = fs.createReadStream(filePath);
                        res.setHeader('Content-Type', 'image/gif');
                        fileStream.pipe(res);
                    }
                });
            } else {
                res.statusCode = 404;
                res.end('Invalid file format');
            }
        } else {
            res.statusCode = 404;
            res.end();
        }
    } catch (e) {
        res.statusCode =500;
        res.end()
    }

});
const port = 3000;
server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});